package load_config

import (
	"log"
	// "path/filepath"
	"sync"

	"github.com/spf13/viper"
)

var (
	once         sync.Once
	GlobalConfig *Config
)

// func init() {
// 	GlobalConfig, _ = GetConfig("config.toml", "config")
// 	log.Println(GlobalConfig)
// }

func GetConfig(fileName string, filePath string) (*Config, error) {
	if GlobalConfig != nil {
		return GlobalConfig, nil
	}

	GlobalConfig, err := LoadDBConfig(fileName, filePath)
	if err != nil {
		panic(err)
	}
	return GlobalConfig, nil
}

type MySQLConfig struct {
	MySQLHost     string
	MySQLPort     int
	MySQLUsername string
	MySQLPassword string
	MySQLDatabase string
	MaxOpenConns  int
}

type DBConfig struct {
	DBUsername string
	DBPassword string
	AuthSource string
}

type All struct {
	CmdbMongoDBUrl string
	NetTypeList    []string
}

type Config struct {
	DBConfig    DBConfig
	All         All
	MySQLConfig MySQLConfig
}

func LoadTomlConfig(fileName string, filePath string) error {
	viper.SetConfigName(fileName) // name of config file (without extension)
	viper.AddConfigPath(filePath) // optionally look for config in the working directory
	viper.SetConfigType("toml")   // REQUIRED if the config file does not have the extension in the name
	err := viper.ReadInConfig()   // Find and read the config file
	return err
}

func LoadDBConfig(fileName string, filePath string) (*Config, error) {
	err := LoadTomlConfig(fileName, filePath)
	if err != nil { // Handle errors reading the config file
		log.Panic(err)
		return nil, err
	}
	var config Config
	err = viper.Unmarshal(&config)
	if err != nil {
		return nil, err
	}
	return &config, nil
}

func LoadConfig() *Config {

	once.Do(func() {
		fileName := "config.toml"
		filePath := "./config"
		var err error
		GlobalConfig, err = LoadDBConfig(fileName, filePath)
		if err != nil {
			panic(err)
		}
	})

	return GlobalConfig
}
